package com.skw.bio.manyToMany.message;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server extends Thread {
    // 用来存放连接上的用户的socket对象的值
    List<Socket> list = new ArrayList<Socket>();
    ExecutorService exec = Executors.newCachedThreadPool();
    ServerSocket serverSocket = null;

    public Server(int port) {
        try {
            serverSocket = new ServerSocket((port));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送消息的线程
    @Override
    public void run() {
        super.run();
        try {
            while (true) {
                // 建立socket接口，accept方法是一个阻塞进程,等到有用户连接才往下走
                // 定义Socket类
                Socket socket = serverSocket.accept();
                //在服务器显示连接上的电脑
                String message = socket.getInetAddress().getHostAddress().toString();
                System.out.println(message+"连接上了");
                // 向用户发送消息
                SendMessageToAllUser("IP为"+message+"的用户加入聊天");
                // 把连接上的用户添加到集合；里面去
                list.add(socket);
                //开始新连接用户的线程，用于该可以一直读取数据
                exec.execute(new readerThread(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void SendMessageToAllUser(String message) {
        for (Socket socket: list) {
            //判断之前保存的连接是否还在
            if (socket!= null && socket.isConnected()) {
                try {
                    OutputStream os = socket.getOutputStream();
                    os.write(message.getBytes());
                    os.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class readerThread implements Runnable {
        InputStream is = null;

        public readerThread(Socket socket) {
            try {
                is = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    SendMessageToAllUser(new String(buf, 0, len));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server(6768);
        server.start();
    }
}
